from django.shortcuts import render,redirect
from django.http.response import HttpResponse
from django.urls import reverse
from django.contrib.auth import authenticate
from user.form import CreateUserForm,LoginForm
from django.contrib.auth import get_user_model, login,logout
User=get_user_model()
# Create your views here.
def create_user(request):
    username=request.POST['username']
    password=request.POST['password']
    comfirm_password=request.POST['comfirm_password']
    try:
        agree=request.POST['checkbox']
    except Exception:
        return HttpResponse('请勾选同意协议')
    if agree !='on':
        return HttpResponse('请同意协议')
    if comfirm_password !=password:
        return  HttpResponse('两次输入密码不一致')
    else:
        try:
            user=User.objects.create_user(username=username,password=password,comfirm_password=None)
        except Exception:
            return HttpResponse("用户名已经存在")
        login(request,user)
        return_url = request.environ.get('HTTP_REFERER', reverse('index'))
        return  redirect(return_url)

def login_user(request):
    loginform=LoginForm(request.POST)
    if loginform.is_valid():
        user=authenticate(**loginform.cleaned_data)
        return_url = request.environ.get('HTTP_REFERER', reverse('index'))
        if user:
            login(request, user)
            return redirect(return_url)
        else:
            return redirect(return_url)
    else:
        return HttpResponse('密码格式不符')



def logout_user(request):

    logout(request)
    return_url = request.environ.get('HTTP_REFERER', reverse('index'))
    return redirect(return_url)




